package com.briup.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.briup.bean.Product;
import com.briup.bean.ShopCatItem;
import com.briup.dao.IShopCartDao;

public class IShopCartDaoImpl implements IShopCartDao{
	private String driver="oracle.jdbc.driver.OracleDriver";
	private String url="jdbc:oracle:thin:@127.0.0.1:1521:XE";
	private String username="estore";
	private String password="estore"; 
	@Override
	public void addProduct(long userId, long productId, int num) {
		// TODO Auto-generated method stub
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			System.out.println("afasafsafas");
			Class.forName(driver);
			conn=DriverManager.getConnection(url, username, password);
			String sql="insert into s_shopcart_item(id,user_id,product_id,num) values(seq_s_shopcart_item.nextval,?,?,?)";
			ps=conn.prepareStatement(sql);
			ps.setLong(1, userId);
			ps.setLong(2, productId);
			ps.setInt(3, num);
			ps.execute();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(ps!=null)ps.close();
				if(conn!=null)conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public List<ShopCatItem> getShopCartByUserId(long userId) {
		// TODO Auto-generated method stub
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		List<ShopCatItem> list=new ArrayList<>();
		try {
			Class.forName(driver);
			conn=DriverManager.getConnection(url, username, password);
			String sql="select p.name,p.price,p.img,s.num from s_product p,s_shopcart_item s where s.user_id=? and p.id=s.product_id";
			ps=conn.prepareStatement(sql);
			ps.setLong(1, userId);
			rs=ps.executeQuery();
			while(rs.next()) {
				String Pname=rs.getString(1);
				double price=rs.getDouble(2);
				String img=rs.getString(3);
				int num=rs.getInt(4);
				Product p=new Product();
				p.setName(Pname);
				p.setPrice(price);
				p.setImg(img);
				ShopCatItem s=new ShopCatItem();
				s.setProduct(p);
				s.setNum(num);
				list.add(s);
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(rs!=null)rs.close();
				if(ps!=null)ps.close();
				if(conn!=null)conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return list;
	}

}
